<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">后台管理系统</div>
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="账号密码登录" name="first">
          <el-form
              :model="accountParam"
              :rules="rules"
              ref="accountLogin"
              label-width="0px"
              class="ms-content"
          >
            <el-form-item prop="username">
              <el-input
                  v-model="accountParam.username"
                  placeholder="请输入用户名"
              >
                <template #prepend>
                  <el-button icon="el-icon-user"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  type="password"
                  placeholder="请输入密码"
                  v-model="accountParam.password"
                  @keyup.enter="accountSubmitForm()"
              >
                <template #prepend>
                  <el-button icon="el-icon-lock"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <div class="login-btn">
              <el-button type="primary" @click="accountSubmitForm()"
              >登录
              </el-button>
            </div>

            <el-link
                href="https://beian.miit.gov.cn/"
                target="_blank"
                :underline="false"
                type="info"
            >
              <el-image
                  style="vertical-align: -2px; margin-right: 4px"
                  src="//gw.alicdn.com/tfs/TB1jwakrbH1gK0jSZFwXXc7aXXa-20-20.png"
              ></el-image>
              粤ICP备2021101153号
            </el-link>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="手机验证码" name="second">
          <el-form
              :model="mobileParam"
              :rules="rules"
              ref="mobileLogin"
              label-width="0px"
              class="ms-content"
          >
            <el-form-item prop="mobile">
              <el-input v-model="mobileParam.mobile" placeholder="请输入手机号">
                <template #prepend>
                  <el-button icon="el-icon-phone"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input
                  placeholder="请输入验证码"
                  v-model="mobileParam.captcha"
                  @keyup.enter="moblieSubmitForm()"
              >
                <template #prepend>
                  <el-button icon="el-icon-lock"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary">
                <span v-show="mobileShow" @click="getMobileCaptcha(mobileParam.mobile)"
                >获取验证码</span
                >
                <span v-show="!mobileShow" class="count"
                >{{ mobileCount }} s</span
                ></el-button
              >
            </el-form-item>
            <div class="login-btn">
              <el-button type="primary" @click="mobileSubmitForm()"
              >登录
              </el-button>
            </div>

            <el-link
                href="https://beian.miit.gov.cn/"
                target="_blank"
                :underline="false"
                type="info"
            >
              <el-image
                  style="vertical-align: -2px; margin-right: 4px"
                  src="//gw.alicdn.com/tfs/TB1jwakrbH1gK0jSZFwXXc7aXXa-20-20.png"
              ></el-image>
              粤ICP备2021101153号
            </el-link>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="邮箱验证码" name="third">
          <el-form
              :model="mailParam"
              :rules="rules"
              ref="mailLogin"
              label-width="0px"
              class="ms-content"
          >
            <el-form-item prop="mail">
              <el-input v-model="mailParam.mail" placeholder="请输入邮箱">
                <template #prepend>
                  <el-button icon="el-icon-box"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input
                  placeholder="请输入验证码"
                  v-model="mailParam.captcha"
                  @keyup.enter="mailSubmitForm()"
              >
                <template #prepend>
                  <el-button icon="el-icon-lock"></el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary">
                <span v-show="mailShow" @click="getMailCaptcha(mailParam.mail)"
                >获取验证码</span
                >
                <span v-show="!mailShow" class="count"
                >{{ mailCount }} s</span
                ></el-button
              >
            </el-form-item>
            <div class="login-btn">
              <el-button type="primary" @click="mailSubmitForm()"
              >登录
              </el-button>
            </div>

            <el-link
                href="https://beian.miit.gov.cn/"
                target="_blank"
                :underline="false"
                type="info"
            >
              <el-image
                  style="vertical-align: -2px; margin-right: 4px"
                  src="//gw.alicdn.com/tfs/TB1jwakrbH1gK0jSZFwXXc7aXXa-20-20.png"
              ></el-image>
              粤ICP备2021101153号
            </el-link>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="扫码登录" name="four">
          <el-form label-width="0px" class="ms-content">
            <iframe
                sandbox="allow-scripts allow-top-navigation allow-same-origin"
                width="400"
                height="400"
                frameborder="0"
                allowTransparency="true"
                :src="wechatQrcode"
            ></iframe>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="container">
        <el-button type="primary" @click="handleRegister()">注册</el-button>
      </div>
    </div>
  </div>

  <div>
    <!-- 用户注册弹出框 -->
    <el-dialog
        title="用户注册"
        v-model="registerVisible"
        width="50%"
        @closed="closed"
        @keyup.enter="registerSubmitForm()"
    >
      <el-form ref="registerForm" :model="registerForm" :rules="rules" label-width="150px">
        <el-form-item prop="mobile">
          <el-input v-model="registerForm.mobile" placeholder="请输入手机号">
            <template #prepend>
              <el-button icon="el-icon-phone"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input
              placeholder="请输入验证码"
              v-model="registerForm.captcha"
              @keyup.enter="registerSubmitForm()"
          >
            <template #prepend>
              <el-button icon="el-icon-lock"></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary">
                <span v-show="mobileShow" @click="getMobileCaptcha(registerForm.mobile)"
                >获取验证码</span
                >
            <span v-show="!mobileShow" class="count"
            >{{ mobileCount }} s</span
            ></el-button
          >
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="registerSubmitForm()">注册</el-button>
          <el-button @click="registerVisible = false">返回登录</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {getAccessTokenApi} from "../api/mgt/power/auth";
import {smsSendCaptchaApi} from "../api/setup/sms";
import {mailSendCaptchaApi} from "../api/setup/mail";
import {getWechatMpQrCodeApi} from "../api/setup/wechat";
import {userSaveBySmsApi} from "../api/mgt/power/user";

import {ElMessage} from "element-plus";
import {toFormData} from "axios";

const clientId = process.env.VUE_APP_CLIENT_ID;
const clientSecret = process.env.VUE_APP_CLIENT_SECRET;
const smsTplCode = process.env.VUE_APP_SMS_TPL_CODE;
const mailTplCode = process.env.VUE_APP_MAIL_TPL_CODE;
const wechatMpCode = process.env.VUE_APP_WECHAT_MP_CODE;
export default {
  data() {
    return {
      activeName: "first",
      mobileShow: true,
      mobileCount: "",
      mobileTimer: null,
      mailShow: true,
      mailCount: "",
      mailTimer: null,
      wechatQrcode: "",
      accountParam: {
        username: "",
        password: "",
        client_id: clientId,
        client_secret: clientSecret,
        grant_type: "password",
      },
      mobileParam: {
        code: smsTplCode,
        mobile: "",
        captcha: "",
        client_id: clientId,
        client_secret: clientSecret,
        grant_type: "sms_code",
      },
      mailParam: {
        code: mailTplCode,
        mail: "",
        captcha: "",
        client_id: clientId,
        client_secret: clientSecret,
        grant_type: "mail_code",
      },
      wxParam: {
        wechatMpCode: wechatMpCode,
      },
      registerVisible: false,
      registerForm: {
        code: smsTplCode,
        mobile: "",
        captcha: ""
      },
      rules: {
        username: [
          {required: true, message: "请输入用户名", trigger: "change"},
          {max: 20, message: "长度不能超过20个字符", trigger: "change"},
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "change"},
          {max: 20, message: "长度不能超过20个字符", trigger: "change"},
        ],
        mobile: [
          {required: true, message: "请输入手机号", trigger: "change"},
          {max: 11, message: "长度不能超过11个字符", trigger: "change"},
        ],
        mail: [
          {required: true, message: "请输入邮箱", trigger: "change"},
          {max: 30, message: "长度不能超过30个字符", trigger: "change"},
        ],
        captcha: [
          {required: true, message: "请输入验证码", trigger: "change"},
          {max: 6, message: "长度不能超过6个字符", trigger: "change"},
        ],
      },
    };
  },
  created() {
    this.$store.commit("clearTags");
  },
  methods: {
    handleClick(tab) {
      if (tab.props.name == "four") {
        this.setWxerwma();
      }
    },
    setWxerwma() {
      getWechatMpQrCodeApi({state: this.wxParam.wechatMpCode}).then((res) => {
        this.wechatQrcode = res?.bizData;
      });
    },
    accountSubmitForm() {
      this.$refs.accountLogin.validate((valid) => {
        if (valid) {
          const formData = toFormData(this.accountParam);
          getAccessTokenApi(formData).then((res) => {
            const tips = "登录成功，一秒后跳至主页";
            this.$message.success({
              message: tips,
              duration: 1 * 1000,
              onClose: () => {
                const data = {...res.bizData};
                this.$store.commit("setUserToken", data);
                this.$router.push("/");
              },
            });
          });
        } else {
          return false;
        }
      });
    },
    mobileSubmitForm() {
      this.$refs.mobileLogin.validate((valid) => {
        if (valid) {
          const formData = toFormData(this.mobileParam);
          getAccessTokenApi(formData).then((res) => {
            const tips = "登录成功，一秒后跳至主页";
            this.$message.success({
              message: tips,
              duration: 1 * 1000,
              onClose: () => {
                const data = {...res.bizData};
                this.$store.commit("setUserToken", data);
                this.$router.push("/");
              },
            });
          });
        } else {
          return false;
        }
      });
    },
    mailSubmitForm() {
      this.$refs.mailLogin.validate((valid) => {
        if (valid) {
          const formData = toFormData(this.mailParam);
          getAccessTokenApi(formData).then((res) => {
            const tips = "登录成功，一秒后跳至主页";
            this.$message.success({
              message: tips,
              duration: 1 * 1000,
              onClose: () => {
                const data = {...res.bizData};
                this.$store.commit("setUserToken", data);
                this.$router.push("/");
              },
            });
          });
        } else {
          return false;
        }
      });
    },
    getMobileCaptcha(mobile) {
      if (mobile == "") {
        return ElMessage.error({
          message: "手机号不能为空",
          duration: 1 * 1000,
        });
      }
      smsSendCaptchaApi({
        code: smsTplCode,
        mobile: mobile,
      }).then(() => {
      });
      const TIME_COUNT = 60;
      if (!this.mobileTimer) {
        this.mobileCount = TIME_COUNT;
        this.mobileShow = false;
        this.mobileTimer = setInterval(() => {
          if (this.mobileCount > 0 && this.mobileCount <= TIME_COUNT) {
            this.mobileCount--;
          } else {
            this.mobileShow = true;
            clearInterval(this.mobileTimer);
            this.mobileTimer = null;
          }
        }, 1000);
      }
    },
    getMailCaptcha(mail) {
      if (mail == "") {
        return ElMessage.error({
          message: "邮箱不能为空",
          duration: 1 * 1000,
        });
      }
      mailSendCaptchaApi({
        tplCode: mailTplCode,
        mail: mail,
      }).then(() => {
      });
      const TIME_COUNT = 60;
      if (!this.mailTimer) {
        this.mailCount = TIME_COUNT;
        this.mailShow = false;
        this.mailTimer = setInterval(() => {
          if (this.mailCount > 0 && this.mailCount <= TIME_COUNT) {
            this.mailCount--;
          } else {
            this.mailShow = true;
            clearInterval(this.mailTimer);
            this.mailTimer = null;
          }
        }, 1000);
      }
    },
    handleRegister() {
      if (this.$refs.registerForm != undefined) {
        this.$refs['registerForm'].resetFields();
      }
      this.registerVisible = true;
    },
    registerSubmitForm() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          userSaveBySmsApi(this.registerForm).then((res) => {
            const tips = "注册成功，一秒后跳至登录页面";
            this.$message.success({
              message: tips,
              duration: 1 * 1000,
              onClose: () => {
                this.registerVisible = false;
              },
            });
          });
        } else {
          return false;
        }
      });
    }
  },
};
</script>

<style scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../assets/img/login-bg.jpg);
  background-size: 100%;
}

.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #000;
  border-bottom: 1px solid #ddd;
}

.ms-login {
  position: absolute;
  left: 50%;
  top: 40%;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(231, 210, 227, 1);
  overflow: hidden;
}

.ms-content {
  padding: 30px 30px;
}

.login-btn {
  text-align: center;
}

.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}

.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #fff;
}

.ms-login .impowerBox .qrcode {
  width: 200px;
}

.ms-login .impowerBox .title {
  display: none;
}

.ms-login .impowerBox .info {
  width: 200px;
}

.ms-login .status_icon {
  display: none;
}

.ms-login .impowerBox .status {
  text-align: center;
}
</style>
